package br.edu.ufcg.fpc.locks;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Bakery lock using atomic operations.
 * 
 * @author Demontie Junior
 * @author Leandro Brito
 * 
 */
public class BakeryLockAO implements BakeryLockIF {

	volatile int[] numbers;
	AtomicInteger last; //AtomicLong (verificar overflow do contador)

	public BakeryLockAO(int n) {
		last = new AtomicInteger(0);
		numbers = new int[n];
		for (int i = 0; i < n; i++) {
			numbers[i] = 0;
		}
	}

	@Override
	public void lock(int id) {
		// Porta de acesso...
		numbers[id] = last.addAndGet(1);
		
		// Busy Wait
		for (int j = 0; j < numbers.length; j++) {
			while ((numbers[j] != 0) && (numbers[j] < numbers[id])); // nunca ha empate
		}
	}

	@Override
	public void unlock(int id) {
		numbers[id] = 0;
	}

}
